package com.beemans.topon

import android.content.Context
import android.widget.FrameLayout
import androidx.lifecycle.LifecycleOwner
import com.anythink.core.api.ATAdConst
import com.anythink.core.api.ATAdInfo
import com.anythink.core.api.ATSDK
import com.anythink.nativead.api.ATNativeAdView
import com.anythink.network.toutiao.TTATInitManager
import com.beemans.topon.ads.*
import com.beemans.topon.data.TpConfig
import com.beemans.topon.kts.convertCustomMap
import com.beemans.topon.log.Logger

/**
 * @author tiamosu
 * @date 2020/7/2.
 */
object TopOn {
    private val TAG by lazy { this::class.java.simpleName }

    /**
     * 全局配置
     */
    internal var tpConfig: TpConfig? = null
        private set

    /**
     * 是否有全屏广告正在加载（广告请求 + 广告展示）
     */
    val isFullAdLoading: Boolean
        get() = TpSplashAd.isAdLoading() || TpInsertAd.isAdLoading() || TpRewardAd.isAdLoading()

    fun init(context: Context, tpConfig: TpConfig) {
        this.tpConfig = tpConfig

        //设置全局流量分组
        tpConfig.globalCustom?.apply {
            val newCustomMap = convertCustomMap(customKeyResponse, customMap)
            if (newCustomMap.isNotEmpty()) {
                ATSDK.initCustomMap(newCustomMap)
                Logger.logI(TAG, "global customMap:$newCustomMap")
            }
        }

        //针对Placement设置流量分组
        tpConfig.placementCustoms?.forEach { response ->
            val newCustomMap = convertCustomMap(response.customKeyResponse, response.customMap)
            if (newCustomMap.isNotEmpty()) {
                ATSDK.initPlacementCustomMap(response.placementId, newCustomMap)
                Logger.logI(TAG, "placement customMap:$newCustomMap")
            }
        }

        //关于广告平台的合规应用下载弹窗
        //穿山甲
        TTATInitManager.getInstance().setIsOpenDirectDownload(tpConfig.isOpenDirectDownload)

        //开启日志功能
        if (tpConfig.logEnabled) {
            ATSDK.setNetworkLogDebug(true)
            ATSDK.integrationChecking(context.applicationContext)
        }

        //个性化广告推送配置
        val status = if (tpConfig.isPersonalizedAds)
            ATAdConst.PRIVACY.PERSIONALIZED_ALLOW_STATUS else ATAdConst.PRIVACY.PERSIONALIZED_LIMIT_STATUS
        ATSDK.setPersonalizedAdStatus(status)

        //隐私合规配置
        tpConfig.privacyConfig?.configure()

        ATSDK.init(context.applicationContext, tpConfig.tpId, tpConfig.tpKey)

        if (tpConfig.logEnabled) {
            ATSDK.testModeDeviceInfo(context.applicationContext) {
                Logger.logI(TAG, "testModeDeviceInfo:$it")
            }
        }
    }

    /**
     * 加载信息流广告
     *
     * @param owner 传入 Activity 或 Fragment
     * @param config 广告配置
     * @param flContainer 广告视图容器
     * @param nativeSelfRender 自渲染配置
     * @param nativeAdCallback 广告回调
     */
    fun loadNativeAd(
        owner: LifecycleOwner,
        config: TpNativeAd.TpNativeAdConfig,
        flContainer: ATNativeAdView? = null,
        nativeSelfRender: INativeSelfRender? = null,
        nativeAdCallback: (TpNativeAd.TpNativeAdCallback.() -> Unit)? = null
    ): TpNativeAd.TpNativeAdLoader {
        return TpNativeAd.TpNativeAdLoader(
            owner = owner,
            config = config,
            flContainer = flContainer,
            nativeSelfRender = nativeSelfRender,
            nativeAdCallback = nativeAdCallback
        ).also(TpNativeAd::start)
    }

    /**
     * 加载信息流广告
     *
     * @param loader 广告加载器
     */
    fun loadNativeAd(loader: TpNativeAd.TpNativeAdLoader): TpNativeAd.TpNativeAdLoader {
        return loader.also(TpNativeAd::start)
    }

    /**
     * 加载横幅广告
     *
     * @param owner 传入 Activity 或 Fragment
     * @param config 广告配置
     * @param flContainer 广告视图容器
     * @param bannerAdCallback 广告回调
     */
    fun loadBannerAd(
        owner: LifecycleOwner,
        config: TpBannerAd.TpBannerAdConfig,
        flContainer: FrameLayout?,
        bannerAdCallback: (TpBannerAd.TpBannerAdCallback.() -> Unit)? = null
    ): TpBannerAd.TpBannerAdLoader {
        return TpBannerAd.TpBannerAdLoader(
            owner = owner,
            config = config,
            flContainer = flContainer,
            bannerAdCallback = bannerAdCallback
        ).also(TpBannerAd::start)
    }

    /**
     * 加载横幅广告
     *
     * @param loader 广告加载器
     */
    fun loadBannerAd(loader: TpBannerAd.TpBannerAdLoader): TpBannerAd.TpBannerAdLoader {
        return loader.also(TpBannerAd::start)
    }

    /**
     * 加载开屏广告
     *
     * @param owner 传入 Activity 或 Fragment
     * @param config 广告配置
     * @param flContainer 广告视图容器
     * @param splashAdCallback 广告回调
     */
    fun loadSplashAd(
        owner: LifecycleOwner,
        config: TpSplashAd.TpSplashAdConfig,
        flContainer: FrameLayout? = null,
        splashAdCallback: (TpSplashAd.TpSplashAdCallback.() -> Unit)? = null
    ): TpSplashAd.TpSplashAdLoader {
        return TpSplashAd.TpSplashAdLoader(
            owner = owner,
            config = config,
            flContainer = flContainer,
            splashAdCallback = splashAdCallback
        ).also(TpSplashAd::start)
    }

    /**
     * 加载开屏广告
     *
     * @param loader 广告加载器
     */
    fun loadSplashAd(loader: TpSplashAd.TpSplashAdLoader): TpSplashAd.TpSplashAdLoader {
        return loader.also(TpSplashAd::start)
    }

    /**
     * 加载插屏广告
     *
     * @param owner 传入 Activity 或 Fragment
     * @param config 广告配置
     * @param insertAdCallback 广告回调
     */
    fun loadInsertAd(
        owner: LifecycleOwner,
        config: TpInsertAd.TpInsertAdConfig,
        insertAdCallback: (TpInsertAd.TpInsertAdCallback.() -> Unit)? = null
    ): TpInsertAd.TpInsertAdLoader {
        return TpInsertAd.TpInsertAdLoader(
            owner = owner,
            config = config,
            insertAdCallback = insertAdCallback
        ).also(TpInsertAd::start)
    }

    /**
     * 加载插屏广告
     *
     * @param loader 广告加载器
     */
    fun loadInsertAd(loader: TpInsertAd.TpInsertAdLoader): TpInsertAd.TpInsertAdLoader {
        return loader.also(TpInsertAd::start)
    }

    /**
     * 加载激励视频
     *
     * @param owner 传入 Activity 或 Fragment
     * @param config 广告配置
     * @param rewardAdCallback 广告回调
     */
    fun loadRewardAd(
        owner: LifecycleOwner,
        config: TpRewardAd.TpRewardAdConfig,
        rewardAdCallback: (TpRewardAd.TpRewardAdCallback.() -> Unit)? = null
    ): TpRewardAd.TpRewardAdLoader {
        return TpRewardAd.TpRewardAdLoader(
            owner = owner,
            config = config,
            rewardAdCallback = rewardAdCallback
        ).also(TpRewardAd::start)
    }

    /**
     * 加载激励视频
     *
     * @param loader 广告加载器
     */
    fun loadRewardAd(loader: TpRewardAd.TpRewardAdLoader): TpRewardAd.TpRewardAdLoader {
        return loader.also(TpRewardAd::start)
    }

    /**
     * 获取信息流缓存
     */
    fun getNativeAdCaches(
        owner: LifecycleOwner,
        placementId: String
    ): List<ATAdInfo> {
        val config = TpNativeAd.TpNativeAdConfig(placementId, adViewWidth = 0, adViewHeight = 0)
        val loader = TpNativeAd.TpNativeAdLoader(owner, config)
        return loader.checkValidAdCaches()
    }

    /**
     * 获取Banner缓存
     */
    fun getBannerAdCaches(
        owner: LifecycleOwner,
        placementId: String
    ): List<ATAdInfo> {
        val config = TpBannerAd.TpBannerAdConfig(placementId, adViewWidth = 0, adViewHeight = 0)
        val loader = TpBannerAd.TpBannerAdLoader(owner, config, null)
        return loader.checkValidAdCaches()
    }

    /**
     * 获取开屏缓存
     */
    fun getSplashAdCaches(
        owner: LifecycleOwner,
        placementId: String
    ): List<ATAdInfo> {
        val config = TpSplashAd.TpSplashAdConfig(placementId)
        val loader = TpSplashAd.TpSplashAdLoader(owner, config)
        return loader.checkValidAdCaches()
    }

    /**
     * 获取插屏缓存
     */
    fun getInsertAdCaches(
        owner: LifecycleOwner,
        placementId: String
    ): List<ATAdInfo> {
        val config = TpInsertAd.TpInsertAdConfig(placementId)
        val loader = TpInsertAd.TpInsertAdLoader(owner, config)
        return loader.checkValidAdCaches()
    }

    /**
     * 获取激励视频缓存
     */
    fun getRewardAdCaches(
        owner: LifecycleOwner,
        placementId: String
    ): List<ATAdInfo> {
        val config = TpRewardAd.TpRewardAdConfig(placementId)
        val loader = TpRewardAd.TpRewardAdLoader(owner, config)
        return loader.checkValidAdCaches()
    }
}